package com.hotel.suqiang.dingdonegurad;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.hotel.suqiang.dingdonegurad.utils.Contants;
import com.hotel.suqiang.dingdonegurad.utils.PackageUtils;
import com.hotel.suqiang.dingdonegurad.utils.SharedPreferencesUtis;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SplashActivity extends AppCompatActivity {

    private  static final  String TAG = "SQ";

    private String url = "http://10.0.30.118:8080/update_info.json";
    private String apkUrl;
    private String desc;
    private String versionCode;
    private ProgressDialog progressDialog;
    private AlertDialog.Builder builder;
    private OkHttpClient client;
    private String filepath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);


        url =  "http://192.168.1.103:8080/update_info.json";

        client = new OkHttpClient();

        initView();
    }

    private void initView() {

        TextView textView = (TextView) findViewById(R.id.tv_splash_version);

        textView.setText("版本:" + PackageUtils.getVersionName(this));

        Log.v(SplashActivity.TAG, "--------------- initView -----------------");

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(SharedPreferencesUtis.getBoolean(SplashActivity.this, Contants.SETTING_UPDATE_KEY, true)){
                    myupdate();
                }else {
                    pushHome();
                }
            }
        }, 2000);



    }




    private  void  myupdate(){

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response.code() == 200){

                    String string = response.body().string();

                    Log.v(SplashActivity.TAG, string);
                    try {
                        JSONObject jsonObject = new JSONObject(string);

                        versionCode = jsonObject.getString("version");

                        desc = jsonObject.getString("desc");

                        apkUrl = jsonObject.getString("url");

                        if (versionCode.equals(PackageUtils.getVersionCode(SplashActivity.this))) {

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SplashActivity.this, "没有新版本", Toast.LENGTH_LONG).show();
                                }
                            });

                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SplashActivity.this, "有新版本,请更新~", Toast.LENGTH_LONG).show();
                                    showUpdateDialog();
                                }
                            });

                        }

                    } catch (JSONException e) {
                            e.printStackTrace();
                    }

                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SplashActivity.this, "http返回失败", Toast.LENGTH_LONG);
                        }
                    });

                }

            }
        });


    }


    protected void showUpdateDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //设置对话框点击不能消失
        //builder.setCancelable(false);
        //设置标题
        builder.setTitle("发现新版本:"+versionCode);
        //设置图标
        builder.setIcon(R.mipmap.ic_launcher);
        //设置描述信息
        builder.setMessage(desc);
        //监听对话框消失的操作
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            //当对话框消失的时候调用
            @Override
            public void onCancel(DialogInterface dialog) {
                //跳转主界面
                pushHome();
            }
        });
        //设置升级和取消按钮
        //升级按钮
        builder.setPositiveButton("立即升级", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //升级操作,下载apk
               downloadApk();

            }
        });
        //取消按钮
        builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //取消升级
                //销毁对话框
                dialog.dismiss();
                //跳转到主界面
                pushHome();
            }
        });
        //显示对话框
        builder.show();
    }

    protected void downloadApk() {

        progressDialog = new ProgressDialog(this);
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);//设置对话框不能消失
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        {
            filepath = Environment.getExternalStorageDirectory()+ "/dingdone.apk";

            Log.i(SplashActivity.TAG, filepath);
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d(SplashActivity.TAG, "文件下载失败");
                    progressDialog.dismiss();
                    pushHome();
                }

                @Override
                public void onResponse(Call call, Response response) {
                    InputStream inputStream = response.body().byteStream();

                    long totalLength = response.body().contentLength();

                    progressDialog.setMax((int) totalLength);
                    long currentLength = 0;

                    FileOutputStream fileOutputStream = null;
                    try {


                         fileOutputStream = new FileOutputStream(new File(filepath));
//
//                        fileOutputStream = SplashActivity.this.openFileOutput(
//                                filepath, Context.MODE_WORLD_READABLE);
                        byte[] buffer = new byte[15];
                        int len = 0;
                        while ((len = inputStream.read(buffer)) != -1) {
                            currentLength += len;
                            fileOutputStream.write(buffer, 0, len);

                            Log.i(SplashActivity.TAG, "totalLength: " + totalLength + " currentLength:" + currentLength);

                            progressDialog.setProgress((int) currentLength);
                        }
                        fileOutputStream.flush();

                        if (totalLength == currentLength){
                            progressDialog.dismiss();
                            Log.d(SplashActivity.TAG, "文件下载成功");

                            try {
                                String command = "chmod " + 666 + " " + filepath;
                                Runtime runtime = Runtime.getRuntime();
                                runtime.exec(command);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            installApk();
                        }else {
                            Log.d(SplashActivity.TAG, "文件下载失败");
                            pushHome();
                        }

                    } catch (IOException e) {
                        Log.i(SplashActivity.TAG, "IOException");
                        e.printStackTrace();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SplashActivity.this, "有新版本,请更新~", Toast.LENGTH_LONG).show();
                            }
                        });
                    }finally {
                        if (fileOutputStream != null) {
                            try {

                                fileOutputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });
        }

    }

    private void installApk() {

        /**
        * <intent-filter>
        <action android:name="android.intent.[.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="content" />  content:// : 内容提供者协议
        <data android:scheme="file" /> file : 从文件中获取数据
        <data android:mimeType="application/vnd.android.package-archive" />
        </intent-filter>
        */
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        //intent.setType("application/vnd.android.package-archive");
        //intent.setData(Uri.fromFile(new File("/mnt/sdcard/mobliesafeSH04_02.apk")));
        intent.setDataAndType(Uri.fromFile(new File(filepath)), "application/vnd.android.package-archive");
        //startActivity(intent);
        //当当前的activity的退出的时候,会调用之前的activity的OnActivityResult方法
        startActivityForResult(intent, 1);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        pushHome();
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void pushHome() {

        Intent intent = new Intent(this, HomeActivity.class);

        startActivity(intent);

        finish();
    }
}
